package com.example.gongzhong1.controller;
import com.example.gongzhong1.utils.MessageUtil;
import com.example.gongzhong1.utils.SignUtil;
import com.example.gongzhong1.utils.TextMessage;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;


/**
* @Description:    微信请求接受入口,如果为get请求,则为微信授权认证;如果为post请求,则为用户操作请求
* @Author:         xiayuxuanmin
* @CreateDate:     2019/6/4 15:37
* @Version:        1.0
 * 微信公众号认证和消息发送都是到这一个接口,我们需要判断到底是认证还是消息
*/
@RestController
public class TestController {
    private Map<String,String> createToRoom = new HashMap<>();//创建者和房间之间的关系(方便容易查找房间创建者和房间之间的关系,所以这里创建了createToRoom和roomToCreate两个map)
    private Map<String,String> roomToCreate = new HashMap<>();//房间和创建者之间的关系
    private Map<String,List<String>> roomToRoles = new HashMap<>();//每个房间对应的角色数组
    private Map<String,List<String>> roomToPlayers = new HashMap<>();//每个房间已经有的玩家
    private Map<String,String> playerToRoom = new HashMap<>();//记录玩家所在的房间号
    private Map<String,String> lastOptions = new HashMap<>();//记录用户的上一个操作
    private String[] roles = new String[]{"狼人","狼人","平民","平民","平民","预言家","女巫","猎人"};
    private Random random = new Random();

    @RequestMapping("getTest")//注意此地的路径,后面的配置会用到
    public String getTest(HttpServletRequest request) throws Exception {
        String signature = request.getParameter("signature");
        //时间戳
        String timestamp = request.getParameter("timestamp");
        //随机数
        String nonce = request.getParameter("nonce");
        //随机字符串
        String echostr = request.getParameter("echostr");
        String method = request.getMethod();
        if(method.equalsIgnoreCase("get")){
            //微信验证
            if (SignUtil.checkSignature(signature,timestamp,nonce)) {
                System.out.println("success1");
                return echostr;
            }
            System.out.println("faile1");
            return "shibai";
        }else if(method.equalsIgnoreCase("post")){
            //用户请求
            //返回的xml数据
            String resMessage = null;
            //默认返回文本消息内容
            String resContent = "这个是默认回复呢";//设置默认的响应信息;即没有进入下面匹配条件的时候,自动回复的响应信息
            String fromUserName = "";
            String toUserName = "";
            String msgType = "";
            try {
                Map<String,String> requestMap = MessageUtil.parseXml(request);
                //发送方账号
                fromUserName = requestMap.get("FromUserName");
                //公众账号
                toUserName = requestMap.get("ToUserName");
                //消息类型
                msgType = requestMap.get("MsgType");
                if ("text".equalsIgnoreCase(msgType)) {
                    //如果是一个文本消息,则获取用户信息内容
                    //消息内容(如果不是msgType不是"text"类型,则可能会没有Content属性)
                    String content = requestMap.get("Content");
                    if (content.contains("123")) {
                        resContent = "123很常见哦";
                    }else if(content.contains("慕容智")){
                        resContent = "《黑鹰传奇》";
                    }else if("join".equalsIgnoreCase(lastOptions.get(fromUserName))){
                        //如果上一步用户执行的是"进入房间"操作
                        //此处发送的理论是一个房间号
                        //获取当前房间的所有角色
                        List<String> roles = roomToRoles.get(content);
                        List<String> players = roomToPlayers.get(content);//获取房间内已经存在的玩家
                        if(roles == null){
                            resContent = "房间号不存在!";
                        }else if(players.size() >= 9){
                            resContent = "房间内玩家已满!";
                        }else {
                            if(!players.contains(fromUserName)){
                                //将当前用户加入到房间里面
                                players.add(fromUserName);
                                //记录用户所在的房间
                                playerToRoom.put(fromUserName,content);
                            }
                            //从当前房间的角色列表中获取一个角色给用户
                            String role = roles.get(players.indexOf(fromUserName));
                            //将角色返回给用户
                            resContent = "您的角色是:"+role;
                        }
                    }
                }else if("event".equalsIgnoreCase(msgType)){//如果是一个事件消息(菜单事件)
                    String event = requestMap.get("Event");//获取事件的类型
                    if("click".equalsIgnoreCase(event)){//代表一个点击事件
                        String eventKey = requestMap.get("EventKey");//获取点击事件的按钮的key
                        if("create".equalsIgnoreCase(eventKey)){
                            //创建房间按钮
                            int roomNumer = random.nextInt(4000);//房间号
                            createToRoom.put(fromUserName,roomNumer+"");//比如说我点了"create",那么此时的fromUserName就是我的账号
                            roomToCreate.put(""+roomNumer,fromUserName);//建立房间和创建者之间的关系
                            List<String> list = Arrays.asList(roles);//生成房间之后,把该房间的每个角色重新排序
                            //打乱数组,目的是以免进来的用户获取角色的时候每次都要生成随机数来获取角色,还要判断角色是否已经使用,这里直接打乱数组,把打乱后的数组的角色供用来的用户使用
                            Collections.shuffle(list);
                            roomToRoles.put(roomNumer+"",list);//建立房间号和角色集合之间的关系
                            resContent = "您创建的房间号是:"+roomNumer;
                            List<String> players = new ArrayList<>();
                            roomToPlayers.put(roomNumer+"",players);
                        }else if("join".equalsIgnoreCase(eventKey)){
                            //需要从房间的角色集合中获取属于自己的角色,必须知道房间号
                            resContent = "请输入房间号:";
                            lastOptions.put(fromUserName,"join");
                        }else if("refresh".equalsIgnoreCase(eventKey)){
                            //刷新房间
                            //如果是创建者,则把所有用户的角色返回
                            String roomNumber = createToRoom.get(fromUserName);
                            if(roomNumber != null){
                                //创建者
                                List<String> roles = roomToRoles.get(roomNumber);
                                List<String> players = roomToPlayers.get(roomNumber);//获取房间内已经存在的玩家
                                StringBuffer stringBuffer = new StringBuffer();
                                for (int i = 0; i < players.size(); i++) {
                                    String player = players.get(i);//获取玩家
                                    String role = roles.get(i);//获取玩家对应角色
                                    stringBuffer.append("玩家:"+player);
                                    stringBuffer.append("的角色是:"+role);
                                    stringBuffer.append("\r\n");
                                }
                                resContent = stringBuffer.toString();
                            }else {
                                //玩家
                                //获取玩家的房间号
                                roomNumber = playerToRoom.get(fromUserName);
                                if(roomNumber != null){
                                   //获取用户对应的角色
                                    String role = roomToRoles.get(roomNumber).get(roomToPlayers.get(roomNumber).indexOf(fromUserName));
                                    resContent = "您的角色是:"+role;
                                }else {
                                    resContent = "您尚未加入任何房间!";
                                }
                            }

                        }else if("recreate".equalsIgnoreCase(eventKey)){
                            //重开一局,就是重新打乱顺序,给每个玩家重新赋予角色
                            String createRoom = createToRoom.get(fromUserName);
                            if(createRoom == null){
                                resContent = "需要创建房间之后才能重新开局!";
                            }else{
                                List<String> roles = roomToRoles.get(fromUserName);
                                Collections.shuffle(roles);
                                resContent = "设置成功,请刷新获取玩家身份!";
                            }
                        }
                    }

                }
            }catch (Exception e){
                resContent = "...抛出了一个异常呢...";
            }
            TextMessage textMessage = new TextMessage();
            textMessage.setToUserName(fromUserName);
            textMessage.setFromUserName(toUserName);
            textMessage.setCreateTime(System.currentTimeMillis());
            textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
            textMessage.setContent(resContent);
            resMessage = MessageUtil.textMessageToXml(textMessage);
            return resMessage;
        }
        return "shibai";
    }
}
